package com.ray.controller;

import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.SimpleDriverDataSource;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.ray.bean.CompanyMaterialTableBean;
import com.ray.bean.DatatablesViewPageBean;
import com.ray.bean.DuplicateOrderUpdateRecordBean;
import com.ray.bean.OrderInfoDetailBean;
import com.ray.exception.ServiceException;
import com.ray.mapper.BasicDataMapper;
import com.ray.mapper.CompanyMaterialMapper;
import com.ray.pojo.MyUser;
import com.ray.service.BasicDataService;
import com.ray.service.DuplicateOrderUpdateRecordsService;
import com.ray.service.OrderService;
import com.ray.service.ProductionUnitFeedService;
import com.ray.util.RequestUtil;
import com.ray.util.ResponseUtil;
import com.ray.util.ReturnStringUtil;

/**
 * 关于投料单的生产单位请求接口
 * <p>
 * Title: ProductionUnitFeedContorller
 * </p>
 * <p>
 * Description:
 * </p>
 * 
 * @author 李斌
 * @date 2018年7月13日
 */
@Controller
@RequestMapping("/productionUnitFeed")
public class ProductionUnitFeedContorller {

	@Autowired
	ProductionUnitFeedService productionUnitFeedService;
	@Autowired
	BasicDataService BasicDataService;
	@Autowired
	OrderService orderService;
	@Autowired
	DuplicateOrderUpdateRecordsService duplicateOrderUpdateRecordsService;
	@Autowired
	CompanyMaterialMapper companyMaterialMapper;
	@Autowired
	BasicDataMapper basicDataMapper;
	@Autowired
	BasicDataService basicDataService;
	/**
	 * 获取生产单位物料可用数 @date 2018年7月13日 上午8:13:16 @author 李斌 @return
	 * Map<String,Object> @throws
	 */
	@RequestMapping("/getProductionUnitCount")
	@ResponseBody
	public Map<String, Object> getProductionUnitCount(HttpServletRequest request) {
		Map<String, Object> map = RequestUtil.getRequestAllParam(request);
		return ResponseUtil.ResponseResult(productionUnitFeedService.getProductionUnitOrderPojo(map));
	}

	/**
	 * 辅助接口(用于批量补全订单) @date 2018年7月17日 上午8:15:37 @author 李斌 @return
	 * Map<String,Object> @throws
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 */
	@RequestMapping("/updateBasicDataAndOrderInfoDetailOnBatch")
	@ResponseBody
	public Map<String, Object> updateBasicDataAndOrderInfoDetailOnBatch(HttpServletRequest request) throws IllegalAccessException, InvocationTargetException {
		Map<String, Object> map = RequestUtil.getRequestAllParam(request);
		MyUser myUser = RequestUtil.getLoginUser(request);
		// 通过八大要素查找相同的订单明细,然后依次传给map,调用以前的单个接口
		if (map.get("oldOrderInfoDetail") == null) {
			throw new ServiceException("订单请求信息为空");
		}
		String orderInfoDetail = map.get("oldOrderInfoDetail").toString();
		OrderInfoDetailBean oldorderInfoDetail = JSONObject.parseObject(orderInfoDetail, OrderInfoDetailBean.class);
		Map<String, Object> orderMap = new HashMap<String, Object>();
		orderMap.put("materialType", oldorderInfoDetail.getMaterialType());
		orderMap.put("orderId", oldorderInfoDetail.getOrderNo());
		orderMap.put("model", oldorderInfoDetail.getMaterialModel());
		orderMap.put("materialFactory", oldorderInfoDetail.getMaterialFactory());
		orderMap.put("color", oldorderInfoDetail.getColor());
		orderMap.put("colorDescription", oldorderInfoDetail.getColorDescription());
		orderMap.put("loginCompany", map.get("loginCompany"));
		orderMap.put("haveYltsTotal",map.get("haveYltsTotal"));
		List<OrderInfoDetailBean> orderInfoDetailList = productionUnitFeedService
				.getOrderIdOnOrderInfoDetailByOrderDetail(orderMap);
		if (orderInfoDetailList == null || orderInfoDetailList.size() < 1) {
			throw new ServiceException("订单信息已补全请勿重复操作");
		}
		//校验
		this.checkMaterialToOrder(map, orderInfoDetailList);
		//补全
		for (OrderInfoDetailBean orderInfoDetailBean : orderInfoDetailList) {
			map.put("orderId", orderInfoDetailBean.getId());
			BasicDataService.updateBasicDataAndOrderInfoDetail(map, myUser);
		}
		return ResponseUtil.ResponseResult("保存成功");
	}

	/**
	 * 通过物料代码和订单信息批量修改订单明细 @date 2018年7月18日 下午3:27:21 @author 李斌 @return
	 * Map<String,Object> @throws
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 */
	@ResponseBody
	@RequestMapping("/updateOrderInfoDetailByMaterialOnBatch")
	public Map<String, Object> updateOrderInfoDetailByMaterialOnBatch(HttpServletRequest request) throws IllegalAccessException, InvocationTargetException {
		Map<String, Object> map = RequestUtil.getRequestAllParam(request);
		// 通过八大要素查找相同的订单明细,然后依次传给map,调用以前的单个接口
		if (map.get("oldOrderInfoDetail") == null) {
			throw new ServiceException("订单请求信息为空");
		}
		String orderInfoDetail = map.get("oldOrderInfoDetail").toString();
		OrderInfoDetailBean oldorderInfoDetail = JSONObject.parseObject(orderInfoDetail, OrderInfoDetailBean.class);
		Map<String, Object> orderMap = new HashMap<String, Object>();
		orderMap.put("materialType", oldorderInfoDetail.getMaterialType());
		orderMap.put("orderId", oldorderInfoDetail.getOrderNo());
		orderMap.put("model", oldorderInfoDetail.getMaterialModel());
		orderMap.put("materialFactory", oldorderInfoDetail.getMaterialFactory());
		orderMap.put("color", oldorderInfoDetail.getColor());
		orderMap.put("colorDescription", oldorderInfoDetail.getColorDescription());
		orderMap.put("loginCompany", map.get("loginCompany"));
		orderMap.put("haveYltsTotal",map.get("haveYltsTotal"));
		List<OrderInfoDetailBean> orderInfoDetailList = productionUnitFeedService
				.getOrderIdOnOrderInfoDetailByOrderDetail(orderMap);
		if (orderInfoDetailList == null || orderInfoDetailList.size() < 1) {
			throw new ServiceException("订单信息已补全请勿重复操作");
		}
		//校验
		orderMap.put("materialCode", map.get("materialCode"));
		CompanyMaterialTableBean companyMaterialTable = companyMaterialMapper.getCompanyMaterialTableByMaterialCode(orderMap);
		map.put("color", companyMaterialTable.getColor());
		map.put("colorDescription", oldorderInfoDetail.getColorDescription());//修改为订单信息的颜色描述 companyMaterialTable.getColorDescription()
		map.put("model", companyMaterialTable.getModel());
		this.checkMaterialToOrder(map, orderInfoDetailList);
		//补全
		for (OrderInfoDetailBean orderInfoDetailBean : orderInfoDetailList) {
			map.put("id", orderInfoDetailBean.getId());
			int row = BasicDataService.updateOrderInfoDetailByCompanyMaterialCode(map);
			if (row < 1) {
				throw new ServiceException("更新订单明细失败");
			}
		}
		return ResponseUtil.ResponseResult("保存成功");
	}

	/**
	 * 辅助接口(用于分配投料数) @date 2018年7月17日 上午10:57:42 @author 李斌 @return
	 * Map<String,Object> @throws
	 */
	@ResponseBody
	@RequestMapping("/saveBatchFeedOrder")
	public Map<String, Object> saveBatchFeedOrder(HttpServletRequest request) throws ServiceException, ParseException {
		Map<String, Object> map = RequestUtil.getRequestAllParam(request);
		String message = productionUnitFeedService.saveBatchFeedOrder(map, request);
		return ResponseUtil.ResponseResult(ReturnStringUtil.SAVE_SUCCESS + "  " + message);
	}

	/**
	 * 辅助接口(汇总查询未生成投料单的订单) @date 2018年7月18日 上午11:32:54 @author 李斌 @return
	 * DatatablesViewPageBean<OrderInfoDetailBean> @throws
	 */
	@ResponseBody
	@RequestMapping("/getOrderInfoDetailByNotFeed")
	public DatatablesViewPageBean<OrderInfoDetailBean> getOrderInfoDetailByNotFeed(HttpServletRequest request) {
		Map<String, Object> map = RequestUtil.getRequestAllParam(request);
		return productionUnitFeedService.getOrderInfoDetailByNotFeed(map);
	}
	
	
	//校验物料是否可被修改
	public void checkMaterialToOrder(Map<String,Object> map,List<OrderInfoDetailBean> orderInfoDetaiList) throws IllegalAccessException, InvocationTargetException {
		List<OrderInfoDetailBean> copeOrderList = new ArrayList<OrderInfoDetailBean>();
		copeOrderList.addAll(orderInfoDetaiList);
		OrderInfoDetailBean copeOrder = new OrderInfoDetailBean();
		int i = 0;
		for(OrderInfoDetailBean orderInfoDetail:orderInfoDetaiList) {
			BeanUtils.copyProperties(orderInfoDetail, copeOrder);
			if(orderInfoDetail.getIsReadColor()!=2) {
				orderInfoDetail.setColor(map.get("color").toString());
				orderInfoDetail.setColorDescription(map.get("colorDescription").toString());
			}
			orderInfoDetail.setMaterialModel(map.get("model").toString());
			boolean isExists = duplicateOrderUpdateRecordsService.checkExists(orderInfoDetail,map.get("loginCompany").toString());
			if(isExists) {
				duplicateOrderUpdateRecordsService.chechIsApproval(orderInfoDetail,map.get("loginCompany").toString());
			}else {
				boolean isEqu = duplicateOrderUpdateRecordsService.orderAndMaterialIsEqually(copeOrder, orderInfoDetail);
				if(!isEqu) {
					String materialCode = (String) map.get("materialCode");
					if(materialCode==null || "".equals(materialCode.trim())) {
						materialCode = duplicateAddMaterial(map,orderInfoDetail);
					}
					DuplicateOrderUpdateRecordBean duplicateOrderUpdateRecordBean = new DuplicateOrderUpdateRecordBean(copeOrder,orderInfoDetail);
					duplicateOrderUpdateRecordBean.setUpdateUserId(map.get("loginUserId").toString());
					duplicateOrderUpdateRecordBean.setUpdateUserName(map.get("loginUserName").toString());
					duplicateOrderUpdateRecordBean.setCompany(map.get("loginCompany").toString());
					duplicateOrderUpdateRecordBean.setMaterialCode(materialCode);
					boolean haveSendMessage = true;
					duplicateOrderUpdateRecordsService.addDuplicateOrderUpdateRecords(duplicateOrderUpdateRecordBean,map,haveSendMessage);
					i++;
				}
			}
			//如果不相等
//			boolean isEqu = duplicateOrderUpdateRecordsService.orderAndMaterialIsEqually(copeOrder, orderInfoDetail);
//			if(!isEqu) {
//				boolean isExists = duplicateOrderUpdateRecordsService.checkExists(orderInfoDetail,map.get("loginCompany").toString());
//				if(isExists) {
//					duplicateOrderUpdateRecordsService.chechIsApproval(orderInfoDetail,map.get("loginCompany").toString());
//				}else {
//					String materialCode = (String) map.get("materialCode");
//					if(materialCode==null || "".equals(materialCode.trim())) {
//						materialCode = duplicateAddMaterial(map,orderInfoDetail);
//					}
//					DuplicateOrderUpdateRecordBean duplicateOrderUpdateRecordBean = new DuplicateOrderUpdateRecordBean(copeOrder,orderInfoDetail);
//					duplicateOrderUpdateRecordBean.setUpdateUserId(map.get("loginUserId").toString());
//					duplicateOrderUpdateRecordBean.setUpdateUserName(map.get("loginUserName").toString());
//					duplicateOrderUpdateRecordBean.setCompany(map.get("loginCompany").toString());
//					duplicateOrderUpdateRecordBean.setMaterialCode(materialCode);
//					boolean haveSendMessage = true;
//					duplicateOrderUpdateRecordsService.addDuplicateOrderUpdateRecords(duplicateOrderUpdateRecordBean,map,haveSendMessage);
//					i++;
//				}
//			}
		}
		Assert.isTrue(i==0, "订单物料信息被修改,请先去审核");
	}
	
	public String duplicateAddMaterial(Map<String,Object> map,OrderInfoDetailBean order) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateString = sdf.format(new Date());
		int isReadColor = order.getIsReadColor();
		String materialCode = null;
		Map<String, Object> unique = new HashMap<String, Object>();
		if (isReadColor == 1) {
			unique.put("color", map.get("color").toString().trim());
			unique.put("materialName", map.get("materialName").toString().trim());
			unique.put("model", map.get("model").toString().trim());
			unique.put("providerName", map.get("providerName").toString().trim());
			unique.put("loginCompany", map.get("loginCompany"));
		} else {
			unique.put("materialName", map.get("materialName").toString().trim());
			unique.put("model", map.get("model").toString().trim());
			unique.put("providerName", map.get("providerName").toString().trim());
			unique.put("loginCompany", map.get("loginCompany").toString().trim());
			unique.put("color", "");
		}
		//20190527
		unique.put("materialDeptId", map.get("materialDeptId"));
		CompanyMaterialTableBean companyMaterial = null;
		List<CompanyMaterialTableBean> companyMaterialList = basicDataMapper.getUniqueCompanyMaterialByDetail(unique);
		if (companyMaterialList != null && companyMaterialList.size() > 0) {
			companyMaterial = companyMaterialList.get(0);
			materialCode = companyMaterial.getMaterialCode();
			Assert.notNull(companyMaterial.getMaterialCode(), "物料代码为空异常");
			// 如果物料类型读取颜色,原物料没有颜色描述,而订单有颜色描述,那么就把订单的颜色描述赋值给物料
			if (isReadColor == 1 && (companyMaterial.getColorDescription() == null
					|| companyMaterial.getColorDescription().equals(""))) {
				String colorDesc = (String) map.get("colorDescription");
				if (colorDesc != null && !colorDesc.trim().equals("")) {
					companyMaterial.setColorDescription(colorDesc);
					basicDataMapper.updateCompanyMaterial(companyMaterial);
				}
			}
		} else {
			companyMaterial = new CompanyMaterialTableBean();
			companyMaterial.setDefaultWarehouse(
					map.get("defaultWarehouse") != null ? map.get("defaultWarehouse").toString() : "");
			if (isReadColor == 1) {
				companyMaterial.setColor(map.get("color") != null ? map.get("color").toString() : "");
				companyMaterial.setColorDescription(
						map.get("colorDescription") != null ? map.get("colorDescription").toString() : "");
			}else {
				companyMaterial.setColor("");
				companyMaterial.setColorDescription("");
			}
			companyMaterial.setMaterialName(map.get("materialName") != null ? map.get("materialName").toString() : "");
			companyMaterial.setModel(map.get("model") != null ? map.get("model").toString() : "");
			companyMaterial.setUnit(map.get("unit") != null ? map.get("unit").toString() : "");
			companyMaterial.setUnitPrice(
					Double.parseDouble(map.get("unitPrice") != "" ? map.get("unitPrice").toString() : "0"));
			companyMaterial
					.setIsEquals(Integer.parseInt(map.get("isEquals") != null ? map.get("isEquals").toString() : "0"));
			companyMaterial.setStatus(map.get("status") != null ? map.get("status").toString() : "");
			companyMaterial.setProviderName(map.get("providerName") != null ? map.get("providerName").toString() : "");
			companyMaterial.setMaterialType(map.get("materialType") != null ? map.get("materialType").toString() : "");
			companyMaterial.setProcurementCycles(Integer
					.parseInt(map.get("procurementCycles") != "" ? map.get("procurementCycles").toString() : "0"));
			companyMaterial.setLastModifyTime(dateString);
			companyMaterial.setLastModifier(map.get("loginUserName").toString());
			companyMaterial.setCompany(map.get("loginCompany").toString());
			companyMaterial.setCreater(map.get("loginUserName").toString());
			companyMaterial.setCreationTime(dateString);
			companyMaterial.setMaterial(map.get("material") != null ? map.get("material").toString() : "");
			if (map.get("transmittance") == null || map.get("transmittance").equals("")) {
				companyMaterial.setTransmittance(null);
			} else {
				companyMaterial.setTransmittance(Double.valueOf(map.get("transmittance").toString()));
			}
			if (map.get("safetyStockMax") != null) {
				companyMaterial.setSafetyStockMax(Double.valueOf(map.get("safetyStockMax").toString()));
			}
			if (map.get("safetyStockMin") != null) {
				companyMaterial.setSafetyStockMin(Double.valueOf(map.get("safetyStockMin").toString()));
			}
			materialCode = BasicDataService.setCompanyMaterialCode(companyMaterial.getProviderName(),
					companyMaterial.getMaterialName());
			companyMaterial.setMaterialCode(materialCode);
			basicDataMapper.insertCompanyMaterialDetail(companyMaterial);
			map.put("companyMaterialTableBean", companyMaterial);
			basicDataService.addCompanyMaterialCountOnMaterial(map);
		}
		return materialCode;
	}

}
